package com.longrise.co.ui.mine.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.co.R;
import com.longrise.co.api.ApiConstants;
import com.longrise.co.api.CommonPara;
import com.longrise.co.ui.carfiles.widget.AddPhotoDialog;
import com.longrise.co.ui.home.model.BindCarInfo;
import com.longrise.co.ui.mine.adapter.MyCarAdapter;
import com.longrise.co.ui.mine.contract.MineContract;
import com.longrise.co.ui.mine.model.MineModel;
import com.longrise.co.ui.mine.presenter.MinePresenter;
import com.longrise.co.utils.Constants;
import com.ly.common.base.BaseFragment;
import com.ly.common.dialog.DialogOnClickListener;
import com.ly.common.dialog.MDAlertDialog;
import com.ly.common.security.EnCryptDeCrypt2;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * Created by luoyang on 2017-7-20.
 */

public class MyCarFragment extends BaseFragment<MinePresenter, MineModel> implements MineContract.MyCarView<BindCarInfo>, SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.OnRecyclerViewItemClickListener, DialogOnClickListener, TakePhoto.TakeResultListener, AddPhotoDialog.OnSelectPhotoListener, InvokeListener {

    @Bind(R.id.head_title)
    TextView headTitle;
    @Bind(R.id.right_btn)
    ImageView rightBtn;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @Bind(R.id.main)
    LinearLayout main;
    @Bind(R.id.search_no_data_tv)
    TextView searchNoDataTv;
    @Bind(R.id.no_data_tip)
    RelativeLayout noDataTip;

    private MyCarAdapter mAdapter;

    private MDAlertDialog mDialog;

    private String mCurrentDeleteCarId;


    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private Uri imageUri;
    private AddPhotoDialog mAddPhotoDialog;
    private String mCarId;
    private OnSuccessListener onSuccessListener;

    public void setOnSuccessListener(OnSuccessListener onSuccessListener1) {
        onSuccessListener = onSuccessListener1;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.common_recylerview_nodata;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    protected void initView() {
        setText(headTitle, "我的车辆");
        rightBtn.setVisibility(View.VISIBLE);
        rightBtn.setImageResource(R.drawable.add);
        main.setBackgroundColor(Color.parseColor("#1A098EDD"));
        searchNoDataTv.setText("抱歉，没有查询到我的车辆");
        initPhotoSelect();

        initRecyclerView();
        mRxManager.on(Constants.RX_EVENT_AUTH_CAR, new Action1<String>() {
            @Override
            public void call(String s) {
                if ("1".equals(s)) {
                    //认证车辆
                    start(CertifiedVehicleFragment.newInstance());
                } else if("3".equals(s)) {
                    //认证成功
                    onRefresh();
                }
            }
        });

        mRxManager.on(Constants.RX_EVENT_DELETE_CAR, new Action1<String>() {
            @Override
            public void call(String s) {
                mCurrentDeleteCarId = s;
                if(mDialog == null) {
                    initCallDialog();
                }
                mDialog.show();
            }
        });

        mRxManager.on(Constants.RX_EVENT_REFRESH_CAR_PHOTO, new Action1<String>() {
            @Override
            public void call(String s) {
                mCarId = s;
                showAddPhotoDialog();
            }
        });

        mRxManager.on(Constants.RX_EVENT_MODIFY_CAR, new Action1<BindCarInfo.ListBean>() {
            @Override
            public void call(BindCarInfo.ListBean s) {
                start(ModifyCarFragment.newInstance(s.getCarno(), s.getVin(), s.getCarid(), s.getCartypecode(), s.getRegisterdate(), s.getEnginenumber()));
            }
        });
        onRefresh();
    }

    private void initRecyclerView() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setColorSchemeColors(Constants.RECYCLER_RGB);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        recyclerView.setLayoutManager(layoutManager);
        mAdapter = new MyCarAdapter(getContext(), null);

        mAdapter.openLoadMore(ApiConstants.PAGE_SIZE_10, true);
        mAdapter.setOnRecyclerViewItemClickListener(this);
        recyclerView.setAdapter(mAdapter);
    }


    @OnClick({R.id.head_back, R.id.right_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.head_back:
                if (onSuccessListener!=null){
                    onSuccessListener.onSuccess();
                }
                _mActivity.onBackPressed();
                break;
            case R.id.right_btn:
                start(CertifiedVehicleFragment.newInstance());
                break;
        }
    }

    public static MyCarFragment newInstance() {
        return new MyCarFragment();
    }

    @Override
    public void requestSuccess(BindCarInfo bindCarInfo) {
        if (bindCarInfo != null && bindCarInfo.getList() != null && bindCarInfo.getList().size() > 0) {
            mAdapter.setNewData(bindCarInfo.getList());
            mAdapter.notifyDataChangedAfterLoadMore(false);
        } else {
            //没有搜索到结果
            noDataTip.setVisibility(View.VISIBLE);
            mAdapter.notifyDataChangedAfterLoadMore(false);
        }
    }

    @Override
    public void onRequestComplete() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void onRefresh() {
        noDataTip.setVisibility(View.GONE);
        mPresenter.getMyCarList(null, true);
    }

    @Override
    public void onItemClick(View view, int i) {

    }

    private void initCallDialog() {
        mDialog = new MDAlertDialog.Builder(getContext())
                .setContentText("确定删除该车辆？")
                .setOnclickListener(this)
                .build();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void deleteCarSuccess() {
        showLongToast("删除车辆成功");
        mRxManager.post(Constants.RX_EVENT_REFRESH_CAR_FILE, null);
        mRxManager.post(Constants.RX_EVENT_REFRESH_MINE, null);
        mRxManager.post(Constants.RX_EVENT_REFRESH_HOME, null);
        onRefresh();
    }

    @Override
    public void modifyCarSuccess() {
        showLongToast("修改车辆照片成功");
        onRefresh();
    }

    @Override
    public void clickLeftButton(View view) {
        if(mDialog != null) {
            mDialog.dismiss();
        }
    }

    @Override
    public void clickRightButton(View view) {
        //删除操作
        mPresenter.deleteCar(mCurrentDeleteCarId);

        if(mDialog != null) {
            mDialog.dismiss();
        }
    }

    private void initPhotoSelect() {
        File file=new File(Environment.getExternalStorageDirectory(), "/temp/"+System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists())file.getParentFile().mkdirs();
        imageUri = Uri.fromFile(file);
        configTakePhotoOption();
    }

    private void configTakePhotoOption(){
        TakePhotoOptions.Builder builder=new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true);
        builder.setCorrectImage(false);
        takePhoto.setTakePhotoOptions(builder.create());

    }

    private void showAddPhotoDialog() {
        if(mAddPhotoDialog == null) {
            mAddPhotoDialog = new AddPhotoDialog(getContext(), R.style.dialog_style);
            mAddPhotoDialog.setCanceledOnTouchOutside(true);
            mAddPhotoDialog.setOnSelectPhotoListener(this);
//          mAddPhotoDialog.create();
        }
        mAddPhotoDialog.show();
    }

    @Override
    public void takeSuccess(TResult result) {
        try {
            if(result != null && result.getImage() != null) {
                String imageInfo = com.longrise.co.utils.StringUtils.File2Base64(result.getImage().getOriginalPath());
                EntityBean bean = new EntityBean();
                String enCarId = EnCryptDeCrypt2.getInstance().EnCrypt(mCarId);
                bean.set("carid", mCarId);
                bean.set("userflag", CommonPara.getInstance().getUserFlag());
                bean.set("carphoto", imageInfo);
                bean.set("user", CommonPara.getInstance().getUser());
                bean.set("sign", enCarId);
                mPresenter.editCar(bean);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void takeFail(TResult result, String msg) {
        showErrorTip(msg);
    }

    @Override
    public void takeCancel() {

    }

    /**
     *  获取TakePhoto实例
     * @return
     */
    public TakePhoto getTakePhoto(){
        if (takePhoto==null){
            takePhoto= (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this,this));
        }
        return takePhoto;
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type=PermissionManager.checkPermission(TContextWrap.of(this),invokeParam.getMethod());
        if(PermissionManager.TPermissionType.WAIT.equals(type)){
            this.invokeParam=invokeParam;
        }
        return type;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type=PermissionManager.onRequestPermissionsResult(requestCode,permissions,grantResults);
        PermissionManager.handlePermissionsResult(getActivity(),type,invokeParam, this);
    }

    @Override
    public void onSelect(int type) {
        switch (type) {
            case AddPhotoDialog.SELECT_ALBUM :
                //选择相册
                takePhoto.onPickFromGallery();
//                        onPickMultiple(MAX_UPLOAD_IMAGE + 1 - mAdapter.getData().size());
                break;
            case AddPhotoDialog.SELECT_PHOTO :
                //拍照
                takePhoto.onPickFromCapture(imageUri);
                break;
            case AddPhotoDialog.SELECT_CANCEL :
                break;
        }
        mAddPhotoDialog.dismiss();
    }
    public interface OnSuccessListener{
        void onSuccess();
    }
}
